package com.pat.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.model.Message;
import com.pat.web.model.Note;
import com.pat.web.model.NoteShare;
import com.pat.web.model.Pet;
import com.pat.web.model.PetCategory;
import com.pat.web.model.PetNote;
import com.pat.web.model.ShareUser;
import com.pat.web.model.User;
import com.pat.web.services.NoteService;

public class NoteController extends Controller {

	/**
	 * 获取自己的和分享的宠物手帐列表
	 */
	public void getPetNoteList() {
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		List<Record> records = Db
				.find("select id,pet_note_name petNoteName,'自己的' belong from note where user_id = ? union "
						+ "select ns.note_id,n.pet_note_name,'被分享' belong from note_share ns join note n on ns.note_id = n.id "
						+ "where ns.share_user_id = ? and ns.is_deleted = 0 and ns.accept = 1", userId, userId);

		for (Record record : records) {
			long noteId = record.getLong("id");
			List<Record> pets = Db
					.find("select p.id,p.user_id userId,p.pet_photo petPhoto,p.pet_nick petNick,p.pet_category_id petCategoryId,p.pet_sex petSex,"
							+ "p.is_sterilized isSterilized,p.pet_birthday petBirthday,p.weight,p.blood_type bloodType,p.create_time createTime,p.update_time updateTime,"
							+ "pc.category_name categoryName from pet p join pet_note pn on p.id= pn.pet_id join pet_category pc on p.pet_category_id = pc.id "
							+ "where pn.note_id = ? and p.is_deleted = 0", noteId);
			record.set("pets", pets);
		}

		ApiResponse response = new ApiResponse();
		response.setData(records);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void createNote() {
		Note note = getBean(Note.class, "");
		ApiResponse response = new ApiResponse();
		// 检查手帐名是否为空
		if (StringUtils.isBlank(note.getPetNoteName())) {
			response.setData("请输入手帐名");
			response.setStatusCode("3001");
			renderJson(response);
			return;
		}
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		// 检查该用户是否存在该手帐
		Note existed = Note.dao.findFirst("select * from note where user_id = ? and pet_note_name = ?", userId,
				note.getPetNoteName());
		if (existed != null) {
			response.setData("手帐名已存在");
			response.setStatusCode("3002");
			renderJson(response);
			return;
		}
		// 获取所有宠物id
		Long[] petIds = getParaValuesToLong("petId");
		if (petIds == null || petIds.length == 0) {
			response.setData("请选择要创建手帐的宠物");
			response.setStatusCode("3004");
			renderJson(response);
			return;
		}
		StringBuffer sbsql = new StringBuffer("select id,pet_category_id from pet where id in ( ");
		for (Long petId : petIds) {
			sbsql.append(petId).append(",");
		}
		String sql = sbsql.substring(0, sbsql.length() - 1);
		sql += " )";
		List<Pet> petsCategory = Pet.dao.find(sql);
		if (petsCategory == null || petsCategory.size() == 0) {
			response.setData("宠物不存在，请检查");
			response.setStatusCode("2004");
			renderJson(response);
			return;
		}
		// 检查所有宠物是否是同类型宠物
		PetCategory firstCategory = PetCategory.dao.findFirst("select * from pet_category where id = ?",
				petsCategory.get(0).getPetCategoryId());
		for (Pet pet : petsCategory) {
			PetCategory category = PetCategory.dao.findFirst("select * from pet_category where id = ?",
					pet.getPetCategoryId());
			if (!(firstCategory.getParentId().equals(category.getParentId()))) {
				response.setData("一套手帐只能添加同一种宠物类型");
				response.setStatusCode("3003");
				renderJson(response);
				return;
			}
		}

		// 保存手帐
		note.setUserId(userId).setCreateTime(new Date()).save();
		long noteId = note.getId();
		for (Pet pet : petsCategory) {
			new PetNote().setNoteId(noteId).setPetId(pet.getId()).setCreateTime(new Date()).save();
		}
		response.setData(noteId);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void getSharedUser() {
		long NoteId = getParaToLong("noteId");
		User user = User.dao.findFirst(
				"select u.id,u.nick_name,u.photo from user u join note_share ns on u.id = ns.share_user_id where ns.note_id = ? and ns.accept = 1",
				NoteId);
		ApiResponse response = new ApiResponse();
		response.setData(user);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void getNotesPets() {
		long NoteId = getParaToLong("noteId");
		List<Record> pets = Db
				.find("select p.id,p.user_id userId,p.pet_photo petPhoto,p.pet_nick petNick,p.pet_category_id petCategoryId,p.pet_sex petSex,"
						+ "p.is_sterilized isSterilized,p.pet_birthday petBirthday,p.weight,p.blood_type bloodType,p.create_time createTime,p.update_time updateTime,"
						+ "pc.category_name categoryName from pet p join pet_note pn on p.id= pn.pet_id join pet_category pc on p.pet_category_id = pc.id "
						+ "where pn.note_id = ? and p.is_deleted = 0", NoteId);
		ApiResponse response = new ApiResponse();
		response.setData(pets);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void renameNote() {
		long noteId = getParaToLong("noteId");
		String petNoteName = getPara("petNoteName");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		Note note = NoteService.noteBelong(noteId, userId);
		if (note != null) {
			// 检查该用户是否存在该手帐
			Note existed = Note.dao.findFirst("select * from note where user_id = ? and pet_note_name = ?", userId,
					petNoteName);
			if (existed != null) {
				response.setStatusCode("3002");
				renderJson(response);
				return;
			}
			note.setPetNoteName(petNoteName).update();
			response.setData("success");
			response.setStatusCode("0000");
			renderJson(response);
			return;
		}
		response.setStatusCode("9999");
		renderJson(response);
	}

	// 获取个人所有手帐及共享用户
	public void getAllNoteAndShareUser() {
		long userId = getAttr(Constants.LOGIN_USER_ID);
		List<Note> notes = Note.dao.find("select * from note where user_id = ?", userId);
		// 循环设置分享用户
		for (Note note : notes) {
			List<User> users = User.dao.find(
					"select u.id,u.mobile,u.nick_name,u.photo,u.sex "
							+ "from user u join note_share ns on u.id = ns.share_user_id where ns.note_id = ? and ns.accept = 1",
					note.getId());
			List<ShareUser> shareUsers = new ArrayList<>();
			if (users != null && users.size() > 0) {
				for (User user : users) {
					shareUsers.add(new ShareUser(user));
				}
			}
			note.setSharedUsers(shareUsers);
		}
		ApiResponse response = new ApiResponse();
		response.setData(notes);
		response.setStatusCode("0000");
		renderJson(JSON.toJSONString(response, SerializerFeature.WriteDateUseDateFormat));
	}

	// 删除手帐共享用户
	public void delShareUser() {
		long noteId = getParaToLong("noteId");
		long shareUserId = getParaToLong("shareUserId");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		// 判断手帐是否属性该用户
		if (NoteService.noteBelong(noteId, userId) != null) {
			NoteShare noteShare = NoteShare.dao.findFirst(
					"select * from note_share where note_id = ? and share_user_id = ? and accept = 1", noteId,
					shareUserId);
			if (noteShare != null) {
				noteShare.delete();
				response.setData("success");
				response.setStatusCode("0000");
				renderJson(response);
				return;
			}
			response.setStatusCode("3005");
			renderJson(response);
			return;
		}
		response.setStatusCode("4002");
		renderJson(response);
	}

	// 删除手帐（同时删除该手帐共享用户）
	public void delNote() {
		long noteId = getParaToLong("noteId");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		// 判断手帐是否属性该用户
		Note note = NoteService.noteBelong(noteId, userId);
		if (note != null) {
			// 删除手帐
			note.delete();
			// 删除手帐共享用户
			Db.update("delete from note_share where note_id = ?", noteId);
			response.setData("success");
			response.setStatusCode("0000");
			renderJson(response);
			return;
		}
		response.setStatusCode("4002");
		renderJson(response);
	}

	public void shareNote() {
		Long noteId = getParaToLong("noteId");
		String shareUser = getPara("shareUser");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		User user = null;
		// 如果是纯数字则校验手机号
		if (NumberUtils.isDigits(shareUser)) {
			user = User.dao.findFirst("select id,mobile from user where mobile = ?", NumberUtils.toLong(shareUser));
		} else { // 如果非纯数据则校验邮箱
			user = User.dao.findFirst("select id,email from user where email = ?", shareUser);
		}
		if (user != null) {
			// 判断该手帐是否已共享过
			NoteShare existNoteShare = NoteShare.dao.findFirst(
					"select * from note_share where note_id = ? and share_user_id = ? and accept = 1", noteId,
					user.getId());
			if (existNoteShare != null) {
				response.setStatusCode("3007");
				renderJson(response);
				return;
			}
			User noteUser = User.dao.findFirst("select * from user where id = ?", userId);
			Note note = Note.dao.findFirst("select * from note where id = ?", noteId);
			// 添加一条note_share
			NoteShare noteShare = new NoteShare();
			noteShare.setNoteId(noteId).setShareUserId(user.getId()).setMobileOrEmail(shareUser)
					.setShareTime(new Date()).save();
			// 系统消息通知
			new Message().setContent("手帐分享：" + noteUser.getNickName() + "分享了手帐“" + note.getPetNoteName() + "”给你，")
					.setUserId(user.getId()).setTargetId(noteShare.getId()).setMessageType(1).setCreateTime(new Date())
					.save();
			response.setData("success");
			response.setStatusCode("0000");
			renderJson(response);
			return;
		}
		response.setStatusCode("1006");
		renderJson(response);
	}

	public void showShareNote() {
		long noteShareId = getParaToLong("noteShareId");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		NoteShare noteShare = NoteShare.dao.findFirst("select * from note_share where id = ? and share_user_id = ?",
				noteShareId, userId);
		if (noteShare != null) {
			Note note = Note.dao.findFirst("select pet_note_name,user_id from note where id = ?",
					noteShare.getNoteId());
			PetNote petNote = PetNote.dao.findFirst("select * from pet_note where note_id = ?", noteShare.getNoteId());
			Pet pet = Pet.dao.findFirst("select * from pet where id = ?", petNote.getPetId());
			PetCategory petCategory = PetCategory.dao.findFirst("select category_name from pet_category where id = ?",
					pet.getPetCategoryId());
			User user = User.dao.findFirst("select nick_name,photo from user where id = ?", note.getUserId());
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("note", note);
			resultMap.put("pet", pet);
			resultMap.put("petCategory", petCategory);
			resultMap.put("user", user);
			response.setData(resultMap);
			response.setStatusCode("0000");
			renderJson(JSON.toJSONString(response, SerializerFeature.WriteDateUseDateFormat));
			return;
		}
		response.setStatusCode("3006");
		renderJson(response);
	}

	public void sharedNoteConfirm() {
		long targetId = getParaToLong("targetId");
		int confirm = getParaToInt("confirm");
		long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		NoteShare noteShare = NoteShare.dao.findFirst(
				"select * from note_share where id = ? and share_user_id = ? and accept = 0", targetId, userId);
		if (noteShare != null) {
			confirm = confirm == 1 ? 1 : -1;
			noteShare.setUpdateTime(new Date()).setAccept(confirm).update();
			response.setData("success");
			response.setStatusCode("0000");
			renderJson(response);
			return;
		}
		response.setStatusCode("3006");
		renderJson(response);
	}
}